<template>
  <div class="login">
    <s-header :name="state.type == 'login' ? '登录' : '注册'" :back="'/home'"></s-header>
    <img class="logo" src="https://s.yezgea02.com/1604045825972/newbee-mall-vue3-app-logo.png" alt="">
    <div  class="login-body login">
      <van-form @submit="onSubmit">
        <van-field
          v-model="state.username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="state.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
       
        <div style="margin: 16px;">
          <div class="link-register" @click="toggle">{{ state.type == 'login' ? '立即注册' : '立即登录'}}</div>
          <van-button round block color="#1baeae" native-type="submit">{{ state.type == 'login' ? '登录' : '注册'}}</van-button>
        </div>
      </van-form>
    </div>
   
  </div>
</template>

<script>

import { useRouter,useRoute } from "vue-router";
import { reactive } from 'vue';
import api from '../../api/user.js';
import md5 from 'js-md5';
import {store} from '../../assets/util.js';
export default {
  name:'myLogin'
}
</script>

<script setup>
import sHeader from '../../components/Header.vue';
const router = useRouter(),
route = useRoute();
const state = reactive({
  username: '',
  password: '',
  username1: '',
  password1: '',
  type: 'login',

})
// 切换登录和注册两种模式
const toggle = () => {
  state.type = state.type=='login'? 'register':'login'
}
// 提交登录或注册表单
const onSubmit = async () => {
 const params = {
    "loginName": state.username,
    "passwordMd5": md5(state.password)
  }
  console.log(params);
  const data = await api.login(params);
  console.log(data);
  //store.set('token', data);
  // 需要刷新页面，否则 axios.js 文件里的 token 不会被重置
  let { from } = route.query;
  console.log(from);
  from ? router.replace(from) : router.push("/home");

}
</script>
<style lang="less">
  .login {
    .logo {
      width: 120px;
      height: 120px;
      display: block;
      margin: 80px auto 20px;
    }
    .login-body {
      padding: 0 20px;
    }
    .login {
      .link-register {
        font-size: 14px;
        margin-bottom: 20px;
        color: #1989fa;
        display: inline-block;
      }
    }
    .register {
      .link-login {
        font-size: 14px;
        margin-bottom: 20px;
        color: #1989fa;
        display: inline-block;
      }
    }
    
  }
</style>
